<template>
	<view class="item-bg">
		<view class="generate-form">
		<!-- 	<view class="form-item">
				<span>分享人id</span><input type="number" v-model="myBusId" placeholder="分享人id" />
			</view>
			<view class="form-item">
				<span>佣金比例</span><input type="number" v-model="rateNum" placeholder="佣金比例(0-100)" /><span>%</span>
			</view> -->
			<view class="form-item">
				<span>生成数量</span><input type="number" v-model="idNum" placeholder="生成数量" /><span>个</span>
			</view>

			<button type="primary" @click="createNullOfflineBusinessList()">生成</button>
		</view>
		<button class="eidt-button" type="primary" v-if="busIds.length"
			@click="saveShareImg">保存到相册（{{busIds[0]}}-{{busIds[busIds.length-1]}}）</button>

		<view class="canvas-posion" v-for="item in busIds" :key="item">
			<canvas :canvas-id="'qrcode'+item" :id="'qrcode'+item"
				:style="{'width': `${size}px`, 'height': `${qrHight}px`}" />

			<canvas :canvas-id="'wificode'+item" :id="'wificode'+item"
				:style="{'width': `${size}px`, 'height': `${size+80}px`}" />
		</view>

		<view class="item_border" v-for="item,idx in codeImg" :key="idx">
			<image :src="item" @click="canstopic(item)" mode="widthFix" style="width: 100%;"></image>
		</view>
		<view class="item_border" v-for="item,idx in wifiImg" :key="idx">
			<image :src="item" @click="canstopic(item)" mode="widthFix" style="width: 100%;"></image>
		</view>

	</view>
</template>

<script>
	const app = getApp();
	import uQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js'
	export default {
		data() {
			return {
				maxNum: '',
				size: 600,
				qrHight: 900,
				margin: 10,
				backgroundColor: '#FFFFFF',
				foregroundColor: '#000000',
				busIds: [],
				bgPath: null,
				idNum: null,
				isRepet: true,
				codeImg: [],
				wifiImg: [],
				myBusId: null
			}
		},
		onLoad(e) {
			this.myBusId = e.id
		},
		methods: {
			createNullOfflineBusinessList() {
				if (!this.idNum) {
					return uni.showToast({
						title: "请输入生成个数",
						icon: "none"
					})
				}

				if (this.isRepet) {
					this.isRepet = false;
					setTimeout(() => {
						this.isRepet = true;
					}, 1500)
					uni.request({
						url: app.globalData.serviceUrl +
							'/UserMiniProgramController/createNullOfflineBusinessList',
						data: {
							key: uni.getStorageSync('userKey'),
							nums: this.idNum
						},
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							if (res.data.state == 1) {
								this.busIds = res.data.data;
								this.huizhi();
							} else {
								uni.showToast({
									title: res.data.notice,
									icon: 'none'
								});
							}
						}
					});
				}

			},
			huizhi() {
				uni.showLoading({
					title: '正在绘制',
					mask: true,
				})
				uni.downloadFile({
					url: "https://zaihuayi.top/picture/static/qrcode_bg.png",
					success: (res) => {
						this.bgPath = res.tempFilePath;
						for (let i in this.busIds) {
							// 被分销商家id
							let pam = this.busIds[i]
							this.generateQrcode('https://zaihuayi.top/payh5/#/?id=' +
								pam, this.busIds[i]);

							this.generateWifi(
								'https://zaihuayi.top/generatewifi?id=' +
								pam, this.busIds[i])

						}
						uni.hideLoading();
					}
				})
			},
			//点击保存到相册
			saveShareImg() {
				if (this.isRepet) {
					this.isRepet = false;
					setTimeout(() => {
						this.isRepet = true;
					}, 1500)
					var that = this;
					uni.showLoading({
						title: '正在保存',
						mask: true,
					})
					for (let i in that.codeImg) {
						uni.saveImageToPhotosAlbum({
							filePath: that.codeImg[i],
							success(sres) {
								console.log(sres);
							},
							fail: function(err) {
								console.log(err);
							},
							complete(scom) {
								if (that.codeImg.length - 1 == i) {
									uni.hideLoading();
								}
							}
						})
					}

					for (let i in that.wifiImg) {
						uni.saveImageToPhotosAlbum({
							filePath: that.wifiImg[i],
							success(sres) {
								console.log(sres);
							},
							fail: function(err) {
								console.log(err);
							},
							complete(scom) {
								if (that.wifiImg.length - 1 == i) {
									uni.hideLoading();
								}
							}
						})
					}
				}
			},
			generateWifi(str, _id) {
				let modules = uQRCode.getModules({
					text: str,
					errorCorrectLevel: uQRCode.errorCorrectLevel.H,
				})

				let size = this.size;
				let margin = 10;
				let xdev = 0;
				let ydev = 0;

				let tileSize = (size - 5 * 2) / modules.length
				// 获取绘图所需的上下文
				let ctx = uni.createCanvasContext('wificode' + _id, this)

				ctx.setFillStyle(this.backgroundColor)
				ctx.fillRect(xdev, ydev, size, size)
				for (var row = 0; row < modules.length; row++) {
					for (var col = 0; col < modules.length; col++) {
						// 计算每一个小块的位置
						var x = col * tileSize + margin + xdev
						var y = row * tileSize + margin + ydev
						var w = tileSize
						var h = tileSize

						var style = modules[row][col] ? this.foregroundColor : this.backgroundColor
						ctx.setFillStyle(style)
						ctx.fillRect(x, y, w, h)
					}
				}

				ctx.setFontSize(30);
				ctx.setFillStyle("#000");
				ctx.setTextAlign("center");
				let text = "WIFI.9102" + _id;
				ctx.fillText(text, this.size / 2, (ydev + size) * 1.08, size);


				ctx.draw();
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: "wificode" + _id,
						success: (res) => {
							this.wifiImg.push(res.tempFilePath)
						}
					})
				}, 500)

			},
			generateQrcode(str, _id) {
				console.log(str);
				let modules = uQRCode.getModules({
					text: str,
					errorCorrectLevel: uQRCode.errorCorrectLevel.H
				})

				let size = 270;
				let margin = 10;
				let xdev = 165;
				let ydev = 315;

				let tileSize = (size - 5 * 2) / modules.length
				// 获取绘图所需的上下文
				let ctx = uni.createCanvasContext('qrcode' + _id, this)
				// 开始绘制
				ctx.drawImage(
					this.bgPath,
					0,
					0,
					this.size,
					this.qrHight,
				);

				ctx.setFillStyle(this.backgroundColor)
				ctx.fillRect(xdev, ydev, size, size)
				for (var row = 0; row < modules.length; row++) {
					for (var col = 0; col < modules.length; col++) {
						// 计算每一个小块的位置
						var x = col * tileSize + margin + xdev
						var y = row * tileSize + margin + ydev
						var w = tileSize
						var h = tileSize

						var style = modules[row][col] ? this.foregroundColor : this.backgroundColor
						ctx.setFillStyle(style)
						ctx.fillRect(x, y, w, h)
					}
				}

				ctx.setFontSize(24);
				ctx.setFillStyle("#000");
				ctx.setTextAlign("center");
				let text = "NO.9102" + _id;
				ctx.fillText(text, this.size / 2, (ydev + size) * 1.08, size);


				ctx.draw();
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: 'qrcode' + _id,
						success: (res) => {
							this.codeImg.push(res.tempFilePath)
						}
					})
				}, 500)
			},
			canstopic(url) {
				uni.previewImage({
					urls: [url] // 需要预览的图片http链接列表
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.generate-form {
		padding: 10px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.form-item {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
			justify-content: flex-start;
			width: 300px;
			span{
				margin-right: 10px;
			}
		}

		input {
			border: 1px solid #999;
			line-height: 44px;
			height: 44px;
			padding: 0 10px;
			border-radius: 5px;
		}

		button {
			width: 100px;
			margin: 0;
		}
	}

	.eidt-button {
		width: 250px;
		margin: 30px auto;
	}

	.item_border {
		margin: 15px;
		padding: 15px 15px;
		border-radius: 15px;
		box-shadow: 0px 3px 5px 0px rgba(207, 207, 207, 0.39);
		background-color: white;
		color: #666;
	}

	.canvas-posion {
		position: absolute;
		top: -1000px;
		left: -1000px;
	}

	.title {
		margin: 15px 0;
		color: #000;
		text-align: center;
	}

	.item-bg {
		background-color: #f2f3f8;
		padding: 10px 0;
		min-height: 100vh;
	}
</style>
